package com.zkadmin.controller;

import java.util.Map;

import org.zkoss.zk.ui.Executions;
import org.zkoss.zk.ui.WrongValueException;
import org.zkoss.zk.ui.event.Event;
import org.zkoss.zk.ui.event.Events;
import org.zkoss.zk.ui.select.annotation.Listen;
import org.zkoss.zk.ui.select.annotation.Wire;
import org.zkoss.zk.ui.select.annotation.WireVariable;
import org.zkoss.zul.Textbox;
import org.zkoss.zul.Window;

import com.zkadmin.entity.SysMenu;
import com.zkadmin.service.SysMenuService;
import com.zkadmin.util.AdminConstants;

@SuppressWarnings("serial")
public class CreateMenuDialogCtrl extends BaseCtrl<Window> {

	@WireVariable
	private SysMenuService sysMenuService;

	private SysMenu menu;

	@Wire
	private Window win;

	@Wire
	private Textbox name;
	@Wire
	private Textbox code;
	@Wire
	private Textbox url;
	@Wire
	private Textbox icon;

	@Override
	protected void init(Window win) {
		this.win = win;
		Map<?, ?> args = Executions.getCurrent().getArg();
		if (args != null && !args.isEmpty()) {
			if (args.containsKey("menu")) {
				menu = (SysMenu) args.get("menu");
			}
		}

		if (menu != null) {
			long ncode = sysMenuService.getMaxMenuCode(menu);
			if (ncode > 10) {
				code.setText(String.valueOf(ncode + 1));
			}
		}
	}

	@Listen("onClick=#okBtn")
	public void createMenu(Event e) {
		if (sysMenuService.findByName(name.getValue()) != null) {
			throw new WrongValueException(name, "\"" + name.getValue() + "\"菜单名称已经存在。");
		}

		if (sysMenuService.findByCode(code.getValue()) != null) {
			throw new WrongValueException(code, "\"" + code.getValue() + "\"菜单标识已经存在。");
		}

		SysMenu newMenu = new SysMenu();
		newMenu.setName(name.getValue());
		newMenu.setCode(code.getValue());
		newMenu.setUrl(url.getValue());
		newMenu.setIcon(icon.getValue());
		sysMenuService.save(newMenu);
		Events.postEvent(AdminConstants.EVENT_ONREFRESH, win, null);
		win.onClose();
	}

	@Listen("onClick=#cancelBtn")
	public void closeDialog(Event e) {
		win.onClose();
	}

}
